<?php
/**
 * Talents come from diligence, and knowledge is gained by accumulation.
 *
 * @author: 晋<657306123@qq.com>
 */

namespace app\common\support;

use app\common\facade\Request;
use think\Db;
use Xin\Support\Str;

/**
 * Class AuthRedirect
 */
class AuthRedirect{

	/**
	 * 获取微信授权地址
	 *
	 * @param string $callback
	 * @return string
	 */
	public static function makeWechatAuthUrl($callback){
		return self::resolveAuthUrl("login/wechat", $callback);
	}

	/**
	 * @param string $action
	 * @param string $callback
	 * @return string
	 */
	private static function resolveAuthUrl($action, $callback){
		$code = Str::nonceHash32();

		self::resolveLog($code, $callback);

		return "https://auth.nlplant.cn/{$action}/auth_code/{$code}";
	}

	/**
	 * 生成记录
	 *
	 * @param string $code
	 * @param string $callback
	 */
	private static function resolveLog($code, $callback){
		self::db()->insert([
			'auth_code'   => $code,
			'callback'    => $callback,
			'status'      => 0,
			'third_code'  => '',
			'ip'          => Request::ip(),
			'expire_time' => Request::time() + 300,
		]);
	}

	/**
	 * 获取授权调整信息
	 *
	 * @param string $authCode
	 * @param string $ip
	 * @return array|\PDOStatement|string|\think\Model|null
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public static function getRedirect($authCode, $ip){
		$authRedirect = self::db()->where('auth_code', $authCode)->find();
		if(empty($authRedirect)){
			return null;
		}

		if($authRedirect['ip'] != $ip){
			return null;
		}

		return $authRedirect;
	}

	/**
	 * @return \think\db\Query
	 */
	private static function db(){
		return Db::name('auth_redirect');
	}

	/**
	 * 更新状态
	 *
	 * @param string $authCode
	 * @throws \think\Exception
	 * @throws \think\exception\PDOException
	 */
	public static function updateStatus($authCode){
		self::db()->where('auth_code', $authCode)->update([
			'status' => 1,
		]);
	}

}
